import MapManageBase from './MapManageBase'
import { IRequestConfig } from '../BaseInterface'
import { textHax } from '../Utils'

/**
* 接口缓存格式
*/
export interface IApiCache {
    data: string;                   // 缓存数据
    createdTime: number;            // 缓存创建时间
}

/**
 * 请求缓存类
 */
export default class ApiCache extends MapManageBase<IApiCache> {
    constructor() {
        super({
            data: '',
            createdTime: Date.now()
        })
    }
    /**
     * 包装 key 使其包含参数
     * @param url
     * @returns 
     */
    packKey(url: string, options: IRequestConfig): string {
        let params = options.params || options.data || url
        return `${url}--hash-${textHax(JSON.stringify(params))}`
    }
    /**
     * 验证缓存是否过期
     * @param url 接口链接
     * @param expires 过期时间
     * @returns true过期 false未过期
     */
    valiOverdue(url: string, expires: number = 0): boolean {
        if (!this.hasData(url)) return true
        if (expires == 0) return false
        let now = Date.now()
        let cacheData = this.getData(url)
        if (now - cacheData.createdTime >= expires) {
            this.deleteData(url)
            return true
        }
        return false
    }
}